/*
 * @Date: 2021-04-29 14:21:23
 * @LastEditors: yangpf-c
 * @LastEditTime: 2021-04-29 16:59:22
 * @FilePath: \react-typescript_demo\src\utils\tools.ts
 */

/**
 * 下载
 * @param path 
 * @param fileName 
 */
export const downloadFile = (path: string, fileName: string): void => {
  let link: HTMLAnchorElement = document.createElement('a')
  link.href = path
  link.download = fileName
  link.target = '_blank'
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 快速生成uuid
 * @returns uuid
 */
export const uuid = (): string => {
  let temp_url: string = URL.createObjectURL(new Blob());
  let uuid: string = temp_url.toString();
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf('/') + 1);
}

/**
 * 获取 URL 参数
 * @param name
 */
export const getUrlParam = (name: string) => {
  const reg = new RegExp('(^|&)' + name.toLowerCase() + '=([^&]*)(&|$)');
  const r: RegExpMatchArray | null = window.location.search
    .substr(1)
    .toLowerCase()
    .match(reg);
  return r != null ? unescape(r[2]) : null;
}

/**
 * 生成随机字符串
 * @param len 长度
 * @returns string
 */
export const generateRandomString = (len: number): string => {
  let i = 0,
    str = '',
    base = 19968,
    range = 10;
  while (i < len) {
    i++;
    const lower = parseInt('' + Math.random() * range);
    str += String.fromCharCode(base + lower);
  }
  return str;
}